<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 

      计算属性允许我们声明性地计算衍生值。然而在有些情况下，我们需要在状态变化时执行一些“副作用”：例如更改 DOM，或是根据异步操作的结果去修改另一处的状态。

      侦听器是用来监听某个数据的改变，从而执行后面的函数

      都能用的情况下，用计算属性(缓存，写的方便)
      只有当异步或者开销较大的时候，只能用侦听器了

      可以有两个参数val和oldVal



     -->
    <div id="app">
      <h2>侦听器</h2>
      <p>count: {{ count }}</p>
      <p>doubleCount: {{ doubleCount }}</p>
      <button @click="count++">btn</button>

      <br />

      <input type="text" v-model="firstname" /> +
      <input type="text" v-model="lastname" /> = {{ fullName }}

      <br />

      <input type="text" v-model="textValue" />

      <hr />

      <p id="p">obj: {{ obj }}</p>
      <button @click="obj.age = 30">btn2</button>

      <p>num: {{ num }}</p>
      <button @click="num++">btn3</button>
      <button @click="start">开启对num的监听</button>
      <button @click="stop">关闭对num的监听</button>
    </div>

    <script src="./vue.js"></script>
    <script>
      let unWatch;

      Vue.createApp({
        data() {
          return {
            count: 1,
            doubleCount: 2,
            firstname: "zhang",
            lastname: "san",
            fullName: "zhangsan",
            textValue: "",
            obj: {
              name: "tom",
              age: 20,
            },

            num: 10,

            // unWatch: undefined,
          };
        },
        watch: {
          count(val, oldVal) {
            console.log("count改变了", val, oldVal);
            setTimeout(() => {
              this.doubleCount = this.count * 2;
            }, 1000);
          },
          firstname(val) {
            this.fullName = val + this.lastname;
          },
          lastname(val) {
            this.fullName = this.firstname + val;
          },
          textValue(val) {
            // fetch({val})
          },

          // obj(val, oldValue) {
          //   console.log("obj改变了");
          // },
          obj: {
            handler(value, oldValue) {
              console.log("obj改变了", document.querySelector("#p").innerHTML);
            },
            // 深度监听
            deep: true,
            // 初始执行一次
            // immediate: true,
            // 相当于将函数在updated的时候执行
            flush: "post",
          },
        },

        // created() {
        //   this.$watch("num", (val) => {
        //     console.log("num:" + val);
        //   });
        // },

        methods: {
          start() {
            unWatch = this.$watch("num", (val) => {
              console.log("num:" + val);
            });
          },
          stop() {
            unWatch();
          },
        },
      }).mount("#app");
    </script>
  </body>
</html>
